package handler

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssnotify/common/constant"
	"ssnotify/common/dto"
	"ssnotify/common/enums/notifyread"
	"ssnotify/common/utils"
	"ssnotify/internal/notify/models"
	"ssnotify/internal/notify/models/query"
)

// 获取通知模板
func getNotifyTemplateList(db *gorm.DB, templateId, templateType string) (notifyTemplateList []models.NotifyTemplate) {
	notifyTemplateModel := &models.NotifyTemplate{}
	notifyTemplateModel.Orm = db
	// 同类型的,配置多条可以逗号间隔
	templateQuery := &query.NotifyTemplateGetReq{
		IdIn: strings.Split(strings.ReplaceAll(templateId, " ", ""), ","),
		Type: templateType,
	}
	var err error
	if notifyTemplateList, err = notifyTemplateModel.FindNotifyTemplate(templateQuery); err != nil {
		logger.Error(err)
		return
	}
	return
}

func addNotifyRecordQueue(notifyData map[string]interface{}, notifyConfig models.NotifyConfig, notifyUser models.NotifyUser, sendResult *models.NotifySendResult) {
	//通知记录对象
	record := models.NotifyRecord{
		Id:         utils.SimpleUUID(),
		Status:     sendResult.SendStatus,
		CreateTime: dto.LocalTime(utils.GetTimePoint(utils.GetStringValueFiled(notifyData, "timestamp"))),
		DeptId:     utils.GetStringValueFiled(notifyData, "deptId"),
		UserId:     notifyUser.UserId,
		UserName:   notifyUser.Username,
		OriginId:   utils.GetStringValueFiled(notifyData, "originId"),
		Type:       utils.GetStringValueFiled(notifyData, "alarmType"),
		ConfigId:   notifyConfig.Id,
		Sn:         utils.GetStringValueFiled(notifyData, "sn"),
		ReadStatus: notifyread.NotRead.Get().Key,
		SendWay:    sendResult.SendWay,
		AgencyId:   notifyUser.AgencyId,
		DevType:    utils.GetStringValueFiled(notifyData, "devType"),
		SendErr:    sendResult.ErrorInfo,
	}
	if len(sendResult.SendContent) > 0 {
		record.Content = utils.InterfaceToStr(sendResult.SendContent)
	}
	//添加到队列中去
	constant.RecordNotifyQueue.Enqueue(record)
}
